package com.handpay.zztong.hp.main.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.RelativeSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.SecureManager;
import com.handpay.framework.swiper.SwiperMode;
import com.handpay.framework.utils.ArithUtil;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.base.callback.BusinessEngineListener;
import com.handpay.zztong.hp.base.fragment.BaseFragment;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.Address;
import com.handpay.zztong.hp.bean.Rate;
import com.handpay.zztong.hp.bean.Rates;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.main.activity.MainActivity;
import com.handpay.zztong.hp.main.model.areatrade.AreaTradeBean;
import com.handpay.zztong.hp.main.model.areatrade.AreaTradeModel;
import com.handpay.zztong.hp.main.model.availabletradetype.AvailableTradeType;
import com.handpay.zztong.hp.main.model.availabletradetype.AvailableTradeTypeModel;
import com.handpay.zztong.hp.main.model.certexpiry.QueryCertNoExpiryDateBean;
import com.handpay.zztong.hp.main.model.certexpiry.QueryCertNoExpiryDateModel;
import com.handpay.zztong.hp.main.model.lowestamount.LowestAccountTransferAmount;
import com.handpay.zztong.hp.main.model.lowestamount.LowestAmountModel;
import com.handpay.zztong.hp.main.model.ratelist.RateListBean;
import com.handpay.zztong.hp.main.model.ratelist.RateListModel;
import com.handpay.zztong.hp.main.widget.RateDialogFragment;
import com.handpay.zztong.hp.permission.PermissionRequestCode;
import com.handpay.zztong.hp.protocol.ATProtocolConstant;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.qualification.activity.IDCardateActivity;
import com.handpay.zztong.hp.swiper.SwiperUtils;
import com.handpay.zztong.hp.swiper.activity.VPOSActivity;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.handpay.zztong.hp.utils.StatusBarUtil;
import com.handpay.zztong.hp.webpay.activity.WebPayWaitingResultActivity;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Hashtable;
import java.util.List;

import static com.handpay.zztong.hp.bean.Address.areaRadius;

@SuppressLint("NewApi")
public class ReceivablesFragment extends BaseFragment implements View.OnClickListener, RateDialogFragment.OnRateViewButtonLinsener {

    private static final String TAG = "ReceivablesFragment";
    protected TextView mInputMoneyet;
    /**
     * 记录当前输入金额的字符串。通过CommonUtils.formatMoney设置到mInputMoneyet
     */
    private String mMoneyText;
    private View receivablesLayout;
    private String webTitle = null;
    private String webUrl = null;
    private int isOpen = 1;
    private int mCertNoExpiryDate = -1;

    /***
     * 支付宝支付
     */
    public static int PAY_TYPE_ALIPAY = 2;
    /***
     * 微信支付
     */
    public static int PAY_TYPE_WECHATPAY = 3;
    public static int PAY_TYPE_WECHATPAY_SCANNER = 4;

    public boolean isOpenBank = true;           //刷卡支付是否打开
    public boolean isOpenAlipay = false;        //支付宝是否打开
    public boolean isOpenWechatPay = false;     //微信反扫是否打开
    public boolean isOpenWechatPayScan = false; //微信正扫是否打开
    public boolean isOpenSannerPay = true;//新版扫描码支付
    public static boolean ISCLEARDATA = false;  // 是否清除数据 第三方支付成功返回的时候清除数据
    private LowestAmountModel mLowestAmountModel;


    private QueryCertNoExpiryDateModel mQueryCertNoExpiryDateModel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLowestAmountModel = new LowestAmountModel();
        mQueryCertNoExpiryDateModel = new QueryCertNoExpiryDateModel();
    }

    private Rate currentSelectRate = null;//当前选择的费率

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        receivablesLayout = inflater.inflate(R.layout.fragment_receivables, container, false);
        initView();
        getLowestAccountTransferAmount();
        if (AccountUtils.getAccountStatus(mActivity) == AccountUtils.AccountStatus.SUCCESS) {
            if (mCertNoExpiryDate == -1) {
                queryCardExpiryDate();
            }
        }
        StatusBarUtil.setTranslucentForImageViewInFragment(getActivity(), 0, null);
        return receivablesLayout;
    }

    /**
     * 获取证件信息是否过期
     */
    private void queryCardExpiryDate() {
        if (!checkMyActivityIsNull()) {
            Hashtable<String, String> params = new Hashtable<>();
            params.put("account", SecureManager.getInstance().des(AccountUtils.getAccountName(mActivity), 1, null));
//            mainActivity.doJsonPost(mainActivity, ZZTongActivity.Do_QueryCertNoExpiryDate, QueryCertNoExpiryDateBean.class, params);
            mQueryCertNoExpiryDateModel.doQueryCertNoExpiryDatePost(mainActivity, params, new BusinessEngineListener<QueryCertNoExpiryDateBean>() {
                @Override
                public void callbackBusinessResponse(QueryCertNoExpiryDateBean queryCertNoExpiryDateBean) {
                    mCertNoExpiryDate = (!TextUtils.isEmpty((queryCertNoExpiryDateBean.getStatus()))) ? CommonUtils.objectToInt(queryCertNoExpiryDateBean.getStatus()) : -1;
                    //-1无相关记录
                    if (!TextUtils.isEmpty(queryCertNoExpiryDateBean.getStatus()) && queryCertNoExpiryDateBean.getStatus().equals("01") || queryCertNoExpiryDateBean.getStatus().equals("03")) {
                        String tipmsg = queryCertNoExpiryDateBean.getRemindMessage();
                        if (mainActivity != null) {
                            mainActivity.showAlertDialog(mainActivity, mainActivity.getString(R.string.tip), tipmsg, false, "去提交", new OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    Intent intent = new Intent(mainActivity, IDCardateActivity.class);
                                    startActivity(intent);
                                }
                            }, "知道了", new OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                        }
                    }
                }
            });
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        //获取可用支付方式
        getTradeType();
        MainActivity.currFragTag = ZZTConstant.FRAGMENT_FLAG_RECEIVABLES;
        restZero();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private int amount = 0;// 银行卡最低收款额度
    private int wechatAmount = 0;// 微信反扫最低收款额度
    private int alipayAmount = 0;// 支付宝最低收款额度
    private int wechatScanpayAmount = 0;//微信正扫最低限额
    private Double selectAmount = 0d;
    private int scanpayAmount = 0;//扫码支付最低限额
    private Rates rates;


    private View findViewById(int id) {
        return receivablesLayout.findViewById(id);
    }

    private void initView() {
        mInputMoneyet = (TextView) findViewById(R.id.rf_tv_input_amount);
        mMoneyText = ZZTConstant.MONEY_ZERO;
        findViewById(R.id.rf_hpKbNum1).setOnClickListener(this);
        findViewById(R.id.rf_hpKbNum2).setOnClickListener(this);
        findViewById(R.id.rf_hpKbNum3).setOnClickListener(this);
        findViewById(R.id.rf_hpKbNum4).setOnClickListener(this);
        findViewById(R.id.rf_hpKbNum5).setOnClickListener(this);
        findViewById(R.id.rf_hpKbNum6).setOnClickListener(this);
        findViewById(R.id.rf_hpKbNum7).setOnClickListener(this);
        findViewById(R.id.rf_hpKbNum8).setOnClickListener(this);
        findViewById(R.id.rf_hpKbNum9).setOnClickListener(this);
        findViewById(R.id.rf_hpKbNum0).setOnClickListener(this);
        findViewById(R.id.rf_hpKbNum00).setOnClickListener(this);
        findViewById(R.id.rf_hpKbCancle).setOnClickListener(this);
        findViewById(R.id.rf_hpKbOk).setOnClickListener(this);
        findViewById(R.id.rf_hpKbDot).setOnClickListener(this);
//        findViewById(R.id.rf_wechat_btn).setOnClickListener(this);
        findViewById(R.id.rf_hpKbCancle).setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                restZero();
                return true;
            }
        });
        mInputMoneyet.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        restZero();
    }

    protected void restZero() {
        SpannableString msp = new SpannableString("¥0.00");
        msp.setSpan(new RelativeSizeSpan(0.5f), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mInputMoneyet.setText(msp);
        mMoneyText = ZZTConstant.MONEY_ZERO;
//        mInputMoneyet.setText(ZZTConstant.MONEY_ZERO);
        ISCLEARDATA = false;
    }

    private void moneyText(String money) {
        mMoneyText = money;
        HPLog.i(HPLog.TAG_RESULT, "--mMoneyText:" + mMoneyText);
        String temp_money = money;
        SpannableString msp = new SpannableString("¥" + CommonUtils.formatMoneyWithSplite(Double.parseDouble(temp_money)));
        msp.setSpan(new RelativeSizeSpan(0.5f), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        mInputMoneyet.setText(currency.format(loanAmount));
        mInputMoneyet.setText(msp);
    }

    private String dealInput(char c) {
        String money = mMoneyText;
        // 如果输入删除
        if ('-' == c) {
            if (ZZTConstant.MONEY_ZERO.equals(money) || money.length() == 1) {
                return ZZTConstant.MONEY_ZERO;
            }
            if ('.' == money.charAt(money.length() - 1)) {
                if (2 == money.length()) {
                    return ZZTConstant.MONEY_ZERO;
                } else {
                    return money.substring(0, money.length() - 2);
                }
            }
            return money.substring(0, money.length() - 1);
        }

        int indexOfDot = money.indexOf(".");
        // 如果当前没有输入小数点，且要输入的不是小数点的时候
        if (-1 == indexOfDot && '.' != c) {
            if (money.length() >= ZZTConstant.MONEY_MAX_LEN) {
                return money;
            }
        }
        // 如果遇到输入0。注意输入00.相当于调用两次输入0
        if ('0' == c) {
            if (ZZTConstant.MONEY_ZERO.equals(money)) {
                return ZZTConstant.MONEY_ZERO;
            }
            // 如果没有小数点，或者没有输入到小数点后两位，仍然可以输入
            if (indexOfDot == -1 || indexOfDot >= (money.length() - 2)) {
                return money + c;
            }
        }
        // 如果遇到输入1~9
        if ('1' <= c && '9' >= c) {
            if (ZZTConstant.MONEY_ZERO.equals(money)) {
                return c + "";
            }
            // 如果没有小数点，或者没有输入到小数点后两位，仍然可以输入
            if (indexOfDot == -1 || indexOfDot >= (money.length() - 2)) {
                return money + c;
            }
        }
        // 如果遇到输入点
        if ('.' == c) {
            if (ZZTConstant.MONEY_ZERO.equals(money)) {
                return "0.";
            }
            // 如果当前money没有'.'
            if (!money.contains(".")) {
                return (money + ".");
            }
        }
        return money;
    }

    public void onClick(View v) {
        char c;
        int i = v.getId();
        if (i == R.id.rf_hpKbNum1) {
            c = '1';
            moneyText(dealInput(c));

        } else if (i == R.id.rf_hpKbNum2) {
            c = '2';
            moneyText(dealInput(c));

        } else if (i == R.id.rf_hpKbNum3) {
            c = '3';
            moneyText(dealInput(c));

        } else if (i == R.id.rf_hpKbNum4) {
            c = '4';
            moneyText(dealInput(c));

        } else if (i == R.id.rf_hpKbNum5) {
            c = '5';
            moneyText(dealInput(c));

        } else if (i == R.id.rf_hpKbNum6) {
            c = '6';
            moneyText(dealInput(c));

        } else if (i == R.id.rf_hpKbNum7) {
            c = '7';
            moneyText(dealInput(c));

        } else if (i == R.id.rf_hpKbNum8) {
            c = '8';
            moneyText(dealInput(c));

        } else if (i == R.id.rf_hpKbNum9) {
            c = '9';
            moneyText(dealInput(c));

        } else if (i == R.id.rf_hpKbNum0) {
            c = '0';
            moneyText(dealInput(c));
        } else if (i == R.id.rf_hpKbNum00) {
            c = '0';
            moneyText(dealInput(c));
            moneyText(dealInput(c));
        } else if (i == R.id.rf_hpKbDot) {
            c = '.';
            moneyText(dealInput(c));
        } else if (i == R.id.rf_hpKbCancle) {
            c = '-';
            moneyText(dealInput(c));
        } else if (i == R.id.rf_hpKbOk) {
            if (chekUserTimeout.isTimeOut()) {
                goLoginWithTimeOut();
                return;
            }
            if (isOpenBank) {
                if (AndPermission.hasPermission(mainActivity, Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.RECORD_AUDIO)) {
                    doOKClickBankCardPay();
                } else {
                    AndPermission.with(this).requestCode(PermissionRequestCode.REQUEST_CODE_PERMISSION_BANKCARDPAY).
                            permission(Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.RECORD_AUDIO).
                            rationale(new RationaleListener() {
                                @Override
                                public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                                    AndPermission.rationaleDialog(mainActivity, rationale).show();
                                }
                            }).send();
                }

            } else {
                mainActivity.showAlertDialog(mainActivity, "", getString(R.string.hint_cannot_paytype), false);
            }

        }
    }

    @Override
    public String getFragmetTitle() {
        return ZZTConstant.FRAGMENT_FLAG_RECEIVABLES;
    }

    @Override
    public ActionBar getFragmentActionBar() {
        super.getFragmentActionBar();
        return new ActionBar(getFragmetTitle());
    }

    /***
     * 获取最低支持的金额
     */
    private void getLowestAccountTransferAmount() {
        if (checkMyActivityIsNull()) {
            return;
        }
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put("version", ClientEngine.VERSION);
        params.put("platform", ClientEngine.MOBILETYPE);
        params.put("channel", ClientEngine.CHANNEL);
        mLowestAmountModel.domLowestAmountModelPost(mainActivity, params, new BusinessEngineListener<LowestAccountTransferAmount>() {
            @Override
            public void callbackBusinessResponse(LowestAccountTransferAmount bean) {
                amount = bean.getAmount();
                wechatAmount = bean.getWechatAmount();
                alipayAmount = bean.getAlipayAmount();
                wechatScanpayAmount = bean.getWechatScanpayAmount();
                scanpayAmount = bean.getScanpayAmount();
                // 插入广发“慧存钱”的一个协议.
//            mainActivity.doPost(mainActivity, ZZTongActivity.Do_ZztAutoPaymentFinancingProduct, treatParams(), true);
            }
        });
    }

    /***
     * 获取交易方式
     */
    private void getTradeType() {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
        AvailableTradeTypeModel mAvailableTradeTypeModel = new AvailableTradeTypeModel();
        mAvailableTradeTypeModel.doAvailableTradeTypeModelPost(mainActivity, params, new BusinessEngineListener<AvailableTradeType>() {
            @Override
            public void callbackBusinessResponse(AvailableTradeType bean) {
                List<AvailableTradeType.ListBean> dataList = bean.getList();
                if (dataList != null) {
                    for (AvailableTradeType.ListBean tradeTypeModle : dataList) {
                        int open = CommonUtils.objectToInt(tradeTypeModle.getIsOpen());
                        int type = CommonUtils.objectToInt(tradeTypeModle.getTradeType());
                        if (open == 1 && type == 1) {
                            isOpenBank = true;
                        } else if (open == 1 && type == 2) {
                            isOpenAlipay = true;
                        } else if (open == 1 && type == 3) {
                            isOpenWechatPay = true;
                        } else if (open == 1 && type == 4) {
                            isOpenWechatPayScan = true;
                        } else if (open == 1 && type == 5) {
                            isOpenSannerPay = true;
                        }
                    }
                    HPLog.i(HPLog.SSX_TAG, "isOpenBank:" + isOpenBank + "|isOpenAlipay:" + isOpenAlipay + "|isOpenWechatPay:" + isOpenWechatPay + "|isOpenWechatPayScan:" + isOpenWechatPayScan + "isOpenSannerPay:" + isOpenSannerPay);
                }
            }
        });
//        mainActivity.doJsonPost(true, mainActivity, DO_GetAvailableTradeTyp, AvailableTradeType.class, params, false);
    }

    /***
     * 刷卡支付
     *
     * @return
     */
    protected boolean doOKClickBankCardPay() {
        if (checkMyActivityIsNull()) {
            return false;
        }
        if (!mainActivity.requestCurrentLocation(true)) {
            return false;
        }
        String content = mInputMoneyet.getText().toString();
        if (TextUtils.isEmpty(content)) {
            return false;
        }
        selectAmount = Double.valueOf(mMoneyText);
        if ((selectAmount * 100) < amount) {
            Toast.makeText(mainActivity, getString(R.string.min_transfer_alert, Double.valueOf(amount) / 100), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (AccountUtils.getAccountStatus(mActivity) == AccountUtils.AccountStatus.NOUPLOAD) {
            // 没有上传资质审核信息，提醒用户提交资质审核
//            mainActivity.showAlertDialog(mainActivity, getString(R.string.tip), getString(R.string.QualificationsPromptVOP_2), true, new OnClickListener() {
//                @Override
//                public void onClick(DialogInterface dialog, int which) {
//                    if (mainActivity.checkSwiperOk(mainActivity, true)) {
//                        //提交资质审核界面
//                        startActivity(mainActivity.getComposeIntent());
//                        dialog.dismiss();
//                    }
//                }
//            }, null);
            mainActivity.showAlertDialog(mainActivity, getString(R.string.tip), getString(R.string.QualificationsPromptVOP_2), false, getString(R.string.qualifications_submit_dialog), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (mainActivity.checkSwiperOk(mainActivity, true)) {
                        //提交资质审核界面
                        startActivity(mainActivity.getComposeIntent());
                    }
                    dialog.dismiss();
                }
            }, getString(R.string.cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            return false;
        } else {
            HPLog.e(HPLog.FDL_TAG, "selectAmount:" + selectAmount);
            if (Address.IS_CHECK_ADDRESS) {
                getAreaTradeValue();
            } else {
                getMuiltRate();
            }
        }
        return true;
    }

    /***
     * 第三方支付
     *
     * @param payType 支付方式
     */
    private void doOKClickWebPay(int payType) {
        if (!mainActivity.requestCurrentLocation(true)) {
            return;
        }
        String content = mInputMoneyet.getText().toString();
        if (TextUtils.isEmpty(content)) {
            return;
        }
        selectAmount = Double.valueOf(mMoneyText);
        double minAmount = scanpayAmount;//扫码支付的最低限额
        if (ArithUtil.mul(selectAmount, 100d) < minAmount) {
            Toast.makeText(mActivity, getString(R.string.min_transfer_scanpay_alert, minAmount / 100), Toast.LENGTH_SHORT).show();
            return;
        }
        SwiperUtils.cleanSwiperData();
        // 打开扫描界面扫描条形码或二维码
        Hashtable<String, Object> params = new Hashtable<String, Object>();
        params.put(ZZTongActivity.ACTION, ZZTongActivity.Action_Transfer1);
        params.put(VPOSActivity.Transfer_Amount_Key, ArithUtil.mul(selectAmount, 100d));
        params.put(ZZTongActivity.PAYTYPE, payType);
        params.put("isOpenWechatPayScan", isOpenWechatPayScan);
        mainActivity.startActivityForResult(mainActivity, WebPayWaitingResultActivity.class, params, ZZTConstant.CONNECT_WEB_PAY_CODE);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AndPermission.onRequestPermissionsResult(requestCode, permissions, grantResults, listener);
    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantPermissions) {
            if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_WEBPAY) {
                doOKClickWebPay(PAY_TYPE_WECHATPAY);
            } else if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_BANKCARDPAY) {
                doOKClickBankCardPay();
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_WEBPAY) {
                Toast.makeText(mainActivity, R.string.message_webpay_permission_failed, Toast.LENGTH_SHORT).show();
            } else if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_BANKCARDPAY) {
                Toast.makeText(mainActivity, R.string.message_bankpay_permission_failed, Toast.LENGTH_SHORT).show();
            }

            if (AndPermission.hasAlwaysDeniedPermission(mainActivity, deniedPermissions)) {
                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(mainActivity, PermissionRequestCode.REQUEST_CODE_SETTING).show();
            }
        }
    };


    private void getAreaTradeValue() {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        new AreaTradeModel().domAreaTradeModelPost(mainActivity, params, new BusinessEngineListener<AreaTradeBean>() {
            @Override
            public void callbackBusinessResponse(AreaTradeBean bean) {
                HPLog.i(HPLog.FDL_TAG, "locationLat = " + bean.getLocationLat() + "  locationLng= " + bean.getLocationLng() + " areaRadius=" + bean.getAreaRadius());
                if (TextUtils.isEmpty(bean.getLocationLat()) || TextUtils.isEmpty(bean.getLocationLng()) || areaRadius <= 0) {
                    Address.reSetAddress();
                } else {
                    Address.setAddress(0.0d, 0.0d, 0.0d);
                    Address.reSetAddress();
                }
                getMuiltRate();
            }
        });
    }

    private void getMuiltRate() {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put("version", ClientEngine.VERSION);
        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
        params.put("businessType", "1");
        params.put("amount", SecureManager.getInstance().des(ArithUtil.mul(selectAmount, 100d) + "", 1, null));
        new RateListModel().doRateListPost(mainActivity, params, new BusinessEngineListener<RateListBean>() {
            @Override
            public void callbackBusinessResponse(RateListBean bean) {
                rates = Rates.generateRates(bean);
//                rates=Rates.generateTestRates();
                if (!rates.isRateNull()) {
                    /*Intent it = new Intent(mainActivity, Muiltate.class);
                    it.putExtra("rates", rates);
                    it.putExtra("amount", selectAmount);
                    it.putExtra("isOpen", isOpen);
                    startActivity(it);
                    restZero();*/
                    showRateListView();
                } else {
                    onVPOS();
                }
            }
        });
    }

    private void showRateListView() {
        RateDialogFragment.newInstance(getString(R.string.hint_titile_rate), rates, false, this).show(getFragmentManager(), "rate");
    }

    @Override
    public void onVPOS() {
        super.onVPOS();
        HPLog.i(HPLog.FDL_TAG, "Receivablefragment onVPOS");
        mainActivity.setMode(SwiperMode.NORMAL_TRANS, false, new Runnable() {
            @Override
            public void run() {
                goTo_VPOS_Activity();
            }
        });
    }

    public void goTo_VPOS_Activity() {
        if (mainActivity.checkVPOS(mainActivity, true)) {

            if (Address.IS_CHECK_ADDRESS && !mainActivity.showNoTranctionMsg()) {
                HPLog.i(HPLog.FDL_TAG, "不在交易范围之内");
                return;
            }
            Hashtable<String, Object> params = new Hashtable<String, Object>();
            params.put(ZZTongActivity.ACTION, ZZTongActivity.Action_Transfer1);
            params.put(VPOSActivity.Transfer_Amount_Key, ArithUtil.mul(selectAmount, 100d));
            params.put("isRateNull", rates.isRateNull());
            if (!rates.isRateNull() && currentSelectRate != null) {
                HPLog.i(HPLog.TAG_RESULT, "rates:" + rates.toString());
                params.put("selectedRate", currentSelectRate.getRateCodeId());
                params.put("isPublicCharge", currentSelectRate.getIsPublicChargeId());
            }
            mainActivity.startActivity(mainActivity, VPOSActivity.class, params);
            currentSelectRate = null;
            // 跳转界面之前，清空金额
            restZero();
        }
    }

    public void goToVPOSActivity() {
        Hashtable<String, Object> params = new Hashtable<String, Object>();
        params.put(ZZTongActivity.ACTION, ZZTongActivity.Action_Transfer1);
        params.put(VPOSActivity.Transfer_Amount_Key, selectAmount * 100);
        params.put("isRateNull", rates.isRateNull());
        mainActivity.startActivity(mainActivity, VPOSActivity.class, params);
        // 跳转界面之前，清空金额
        restZero();
    }

    public void onOkClick(Dialog dialog, Rate obj) {
        HPLog.i(HPLog.TAG_RESULT, obj != null ? obj.toString() : "Error：Rate 对象为null！");
        String temp = obj != null ? obj.getRateAmount() : null;
        if (TextUtils.isEmpty(temp)) {
            Toast.makeText(getActivity(), mainActivity.getString(R.string.hint_data_exception), Toast.LENGTH_LONG).show();
            return;
        }
        dialog.cancel();
        //如果大于0 则继续判断金额
        if (CommonUtils.objectToInt(temp) > 0 && (selectAmount * 100) > Double.parseDouble(temp)) {

            mainActivity.showAlertDialog(mainActivity, mainActivity.getString(R.string.tip), mainActivity.getString(R.string.hint_limit_money, (Double.parseDouble(temp) / 100)), true, new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            return;
        }
        currentSelectRate = obj;
        onVPOS();
    }
}